using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

using ColladaDotNet;
using ColladaDotNet.Pipeline.BSP;
using ColladaDotNet.Pipeline.BSP.Quake3;

namespace Bsp2Unity
{
	class Program
	{
		static void Main(string[] args)
		{
			if (args.Length == 0)
			{
				foreach (var s in Directory.GetFiles(Directory.GetCurrentDirectory(), "*.bsp"))
				{
					Convert(s, Path.ChangeExtension(s, ".dae"));
				}
			}
			else
			{
				foreach (var s in args)
				{
					Convert(s, Path.ChangeExtension(s, ".dae"));
				}
			}
		}

		static void Convert(string source, string dist)
		{
			Console.WriteLine("Converting " + source + " to " + dist);
			using (var s = File.OpenRead(source))
			{
				BSPReader r =new BSPReader();
				r.Transformation = new UniformScaleTransformation(0.02);
				var file = r.Parse(s);

				var c= file.GetColladaFileLeafs(dist);

				var prefix = Path.GetFileNameWithoutExtension(dist);
				var dirName = Path.Combine(Path.GetDirectoryName(dist), "Editor");
				if (!Directory.Exists(dirName))
					Directory.CreateDirectory(dirName);
				using (var f = File.CreateText(Path.Combine(dirName , prefix + "_materials.js")))
				{
					f.WriteLine("//@script ExecuteInEditMode()");
					f.WriteLine("@MenuItem (\"GameObject/"+prefix+"\")");
					
					f.WriteLine("static function Update () {");
					f.WriteLine("var q:Material;");
					f.WriteLine("var t:Texture;");
					foreach (var m in c.library_materials.material)
					{
						var i = m.GetDiffuseImage(c);
						if (i != null)
						{
							var init_from = i.Item as string;
							if (init_from != null)
							{
								f.WriteLine("q = AssetDatabase.LoadAssetAtPath (\"Assets/Materials/" + prefix + "-" + m.id + ".mat\",Material);");
								f.WriteLine("t = AssetDatabase.LoadAssetAtPath (\"Assets/"+init_from.Replace("./","")+"\",Texture);");
								f.WriteLine("if (q && t) q.mainTexture = t;");
							}

						}
					}
					f.WriteLine("AssetDatabase.SaveAssets();");
					f.WriteLine("}");
				}
			}
		}
	}
}
